from flask import Flask, request, render_template_string
import json
from datetime import datetime

app = Flask(__name__)
SAVE_FILE = 'locations.txt'

HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
    <title>位置权限解决方案</title>
    <style>
        .permission-box {
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 2rem;
            max-width: 500px;
            margin: 3rem auto;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            text-align: center;
        }
        .auth-btn {
            background: #2196F3;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background 0.3s;
        }
        .auth-btn:hover {
            background: #1976D2;
        }
        #status {
            margin-top: 1rem;
            color: #666;
            min-height: 1.5rem;
        }
    </style>
</head>
<body>
    <div class="permission-box">
        <h2>位置服务授权</h2>
        <p>本功能需要获取您的位置信息用于服务展示</p>
        <button class="auth-btn" onclick="requestGeoPermission()">
            授权位置访问
        </button>
        <div id="status"></div>

        <!-- 隐私条款链接 -->
        <p style="margin-top: 2rem; font-size: 0.9rem;">
            点击即表示同意我们的
            <a href="/privacy" target="_blank">隐私政策</a>
        </p>
    </div>

    <script>
        function updateStatus(text, isError = false) {
            const status = document.getElementById('status');
            status.innerHTML = text;
            status.style.color = isError ? '#d32f2f' : '#2e7d32';
        }

        function requestGeoPermission() {
            updateStatus('正在请求权限...');

            if (!navigator.geolocation) {
                updateStatus('错误：浏览器不支持地理定位', true);
                return;
            }

            // 先检查当前权限状态
            navigator.permissions.query({ name: 'geolocation' }).then(permissionStatus => {
                if (permissionStatus.state === 'granted') {
                    getLocation();
                } else {
                    // 触发权限请求
                    navigator.geolocation.getCurrentPosition(
                        () => {
                            permissionStatus.onchange = null;
                            getLocation();
                        },
                        error => handleError(error),
                        { maximumAge: 0, timeout: 10000 }
                    );
                }

                // 监听权限状态变化
                permissionStatus.onchange = () => {
                    if (permissionStatus.state === 'granted') {
                        getLocation();
                    }
                }
            });
        }

        async function getLocation() {
            updateStatus('定位中...');

            try {
                const position = await new Promise((resolve, reject) => {
                    navigator.geolocation.getCurrentPosition(resolve, reject, {
                        enableHighAccuracy: true,
                        timeout: 10000,
                        maximumAge: 0
                    });
                });

                // 后续处理...

            } catch (error) {
                handleError(error);
            }
        }

        function handleError(error) {
            const errors = {
                1: '权限被拒绝：请点击地址栏左侧图标允许位置访问',
                2: '位置不可用：请检查设备定位功能是否开启',
                3: '请求超时：请确保网络畅通后重试'
            };
            updateStatus(`❗ ${errors[error.code] || '未知错误'}`, true);

            // 显示重试按钮
            const btn = document.createElement('button');
            btn.className = 'auth-btn';
            btn.style.marginTop = '1rem';
            btn.textContent = '重试定位';
            btn.onclick = requestGeoPermission;
            document.getElementById('status').appendChild(btn);
        }
    </script>
</body>
</html>
"""


@app.route('/')
def index():
    return render_template_string(HTML_TEMPLATE)


@app.route('/save', methods=['POST'])
def save_location():
    try:
        data = request.json
        data['server_time'] = datetime.now().isoformat()

        with open(SAVE_FILE, 'a', encoding='utf-8') as f:
            f.write(json.dumps(data, ensure_ascii=False, indent=2) + ',\n')

        return {'success': True}
    except Exception as e:
        return {'success': False, 'error': str(e)}

# 保持之前的 /save 路由不变

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)